package com.johnny.xia.util.graphql;

import com.alibaba.fastjson.JSON;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.Scalars;
import graphql.execution.SubscriptionExecutionStrategy;
import graphql.schema.*;
import graphql.schema.idl.SchemaGenerator;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.concurrent.atomic.AtomicReference;

public class SubscriptionTest {

    public static void main(String[] args) {
        String auctionId = "";


        String schema = "";

        GraphQLFieldDefinition field = GraphQLFieldDefinition.newFieldDefinition()
                .name("lotId")
                .type(Scalars.GraphQLString)
                .build();

        GraphQLObjectType queryType = GraphQLObjectType.newObject()
                .name("bidStateByAuctionId")
                .field(field)
                .build();

        GraphQLSchema graphQLSchema =GraphQLSchema.newSchema().query(queryType).build();

//        GraphQLSchema graphQLSchema = new SchemaUtil().create();

        GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema)
                .subscriptionExecutionStrategy(new SubscriptionExecutionStrategy())
                .build();

        String query = buildQuery(auctionId);

        ExecutionResult executionResult = graphQL.execute(query);

        Publisher<ExecutionResult> stockPriceStream = executionResult.getData();

        AtomicReference<Subscription> subscriptionRef = new AtomicReference<>();
        stockPriceStream.subscribe(new Subscriber<ExecutionResult>() {

            @Override
            public void onSubscribe(Subscription s) {
                subscriptionRef.set(s);
                s.request(1);
            }

            @Override
            public void onNext(ExecutionResult er) {
                System.out.println(JSON.toJSONString(er.getData()));

                //
                // ask the publisher for one more item please
                //
                subscriptionRef.get().request(1);
            }

            @Override
            public void onError(Throwable t) {
                System.err.println("连接异常");
                t.printStackTrace();
            }

            @Override
            public void onComplete() {
                System.out.println("创建监听成功");
            }
        });



    }

    private static String buildQuery(String auctionId){
      return  "subscription{\n" +
                "  bidStateByAuctionId(id:\""+auctionId+"\"){\n" +
                "    lotId\n" +
                "    currentBid\n" +
                "    numberOfBids\n" +
                "    sold\n" +
                "    closingTime\n" +
                "  }\n" +
                "}";
    }
}
